package com.heima.wemedia.service.Imp;

import java.util.*;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.model.common.constants.message.NewsAutoScanConstants;
import com.heima.model.common.constants.message.NewsUpOrDownConstants;
import com.heima.model.common.constants.message.PublishArticleConstants;
import com.heima.model.common.constants.wemedia.WemediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dto.NewsAuthDTO;
import com.heima.model.wemedia.dto.WmNewsDTO;
import com.heima.model.wemedia.dto.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vo.WmNewsVO;
import com.heima.threadlocal.WmThreadLocalUtils;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsServiceImp extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Value("${file.oss.web-site}") //直接从配置中动态读取
    String webSite;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 内容列表实现
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult getList(WmNewsPageReqDTO dto) {
        //1.校验数据
        dto.checkParam();
        //判断是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "未登录，请先登录!");
        }
        //2.进行分页查询
        Page<WmNews> newsPage = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        //3.如果文章有标题
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            wrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        //4.如果有频道信息
        if (dto.getChannelId() != null) {
            wrapper.eq(WmNews::getId, dto.getChannelId());
        }
        //5.如果有文章状态按照文章信息查询
        if (dto.getStatus() != null) {
            wrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        //6.如果有开始时间结束时间
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            wrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }
        //7.根据用户id查询
        wrapper.eq(WmNews::getUserId, user.getId());
        //8.按照创建时间降序
        wrapper.orderByDesc(WmNews::getPublishTime);
        //9.根据结果进行查询
        IPage<WmNews> page = this.page(newsPage, wrapper);
        List<WmNews> records = page.getRecords();
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), newsPage.getTotal(), records);
        result.setHost(webSite);
        return result;
    }

    /**
     * 文章发布
     *
     * @param dto
     * @return
     */
    @Override
    @GlobalTransactional
    public ResponseResult submitArticle(WmNewsDTO dto) {
        //将文章从请求中封装保存到类中
        WmNews wmNews = getWmNews(dto);
        //3.保存或修改文章
        saveAndUpdateArticle(wmNews);
        //判断当前的文章是否为草稿
        if (WemediaConstants.WM_NEWS_DRAFT_STATUS.equals(wmNews.getStatus())) {
            //直接响应结果不需要添加素材关系
            return ResponseResult.okResult();
        }
        //4.保存文章和素材的关系
        //4.1抽取文章内容中的素材字符串集合
        List<String> listImg = getContentImageToStr(wmNews.getContent());
        //保存文章关联关系 文章
        if (!CollectionUtils.isEmpty(listImg)) {
            saveRelativeInfo(listImg, wmNews.getId(), WemediaConstants.WM_CONTENT_REFERENCE);
        }
        //保存文章封面 引用素材的关联关系
        saveRelativeCover(dto, listImg, wmNews);
        //TODO rabbitMq实现消息发送 发送文章的id交由自动审核
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE,wmNews.getId());
        log.info("成功发送 待审核消息 ==> 队列:{}, 文章id:{}",wmNews.getId());
        return ResponseResult.okResult();
    }
    /**
     * 生成文章封面的 文章素材关系
     * 如果是自动 就需要从内容里面拿封面
     *
     * @param dto
     * @param listImg
     * @param wmNews
     */
    private void saveRelativeCover(WmNewsDTO dto, List<String> listImg, WmNews wmNews) {
        //前端传递过来的封面列表
        List<String> images = dto.getImages();
        //对前端传入的封面类型进行判断
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            //给状态复制
            int size = listImg == null ? 0 : listImg.size();
            //对size的结果进行判断
            if (size > 0 || size <= 2) {
                images = listImg.stream().limit(1).collect(Collectors.toList());
                //单图
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);

            } else if (size > 2) {
                //多图
                images = listImg.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
            } else {
                //无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            wmNews.setImages(ImagesToStr(images));
            this.updateById(wmNews);
        }
        if (!CollectionUtils.isEmpty(images)) {
            //如果前端传递的
            images = images.stream().map(url -> url.replace(webSite, "")).collect(Collectors.toList());
            //保存
            saveRelativeInfo(images, wmNews.getId(), WemediaConstants.WM_IMAGE_REFERENCE);

        }

    }


    /**
     * 保存关联关系
     *
     * @param listImg
     * @param newsId
     * @param type
     */
    private void saveRelativeInfo(List<String> listImg, Integer newsId, Short type) {
        //根据素材路径 和当前用户id查询出对应的 素材的id
        List<Integer> wmMaterialIds = wmMaterialMapper.selectRelationsIds(listImg, WmThreadLocalUtils.getUser().getId());
       /* List<WmMaterial> list = wmMaterialMapper.selectList(
                Wrappers.<WmMaterial>lambdaQuery()
                 //查询路径
                .in(WmMaterial::getUrl, listImg)
                        //查询对应的用户的id
                .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId())
                        //只存入id的值 提高性能
                .select(WmMaterial::getId));*/
        //判断获得素材id的集合是否和传入的路径不相等
        if (wmMaterialIds.size() != listImg.size()) {
            CustException.cust(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST, "素材缺失保存失败!");
        }
        //保存素材文章关系表
   /*     for (WmMaterial wmMaterial : list) {
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            wmNewsMaterial.setMaterialId(wmMaterial.getId());
            wmNewsMaterial.setNewsId(newsId);
            wmNewsMaterial.setType(type);
            wmNewsMaterialMapper.insert(wmNewsMaterial);
        }*/
        wmNewsMaterialMapper.saveRelations(wmMaterialIds, newsId, type);
    }


    /**
     * 抽取文章中的素材的集合
     *
     * @param content
     * @return
     */
    private List<String> getContentImageToStr(String content) {
        //将字符串转变成Map集合
        List<Map> mapList = JSON.parseArray(content, Map.class);
        //stream过滤
        return mapList.stream()
                .filter(map -> WemediaConstants.WM_NEWS_TYPE_IMAGE.equals(map.get("type")))
                .map(url -> String.valueOf(url.get("value")))
                .map(map -> map.replace(webSite, ""))
                .distinct()
                .collect(Collectors.toList());

    }


    //保存或修改文章
    private void saveAndUpdateArticle(WmNews wmNews) {
        //判断数据库中是否存保存过文章
        if (wmNews.getId() == null) {
            this.save(wmNews);
        } else {
            //修改或保存
            //删除原先的素材文章关系表
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaUpdate().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            //修改传入的值更新表
            this.updateById(wmNews);
        }
    }

    //将前端的参数封装到WmNews对象中
    private WmNews getWmNews(WmNewsDTO dto) {
        //0.判断文章的内容是否为空
        if (StringUtils.isBlank(dto.getContent())) {
            CustException.cust(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST, "文章内容不能为空!");
        }
        //1.校验数据 查看是否登录
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "未登录，请先登录!");
        }
        //2.将前端传来的参数封装到 WmNews对象中
        WmNews wmNews = new WmNews();

        BeanUtils.copyProperties(dto, wmNews);
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(wmNews.getType())) {
            wmNews.setType(null);
        }
        //2.1对context中的images进行处理
        List<String> images = dto.getImages();
        //对图片进行处理去除前面的域名
        wmNews.setImages(ImagesToStr(images));
        wmNews.setUserId(user.getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);
        return wmNews;
    }

    /**
     * 将图片路径转换为字符串 并去除路径
     *
     * @param images
     * @return
     */
    private String ImagesToStr(List<String> images) {
        if (CollectionUtils.isEmpty(images)) {
            return null;
        }
        //对集合使用stream进行处理
        return images.stream()
                //将数据中的路径替换
                .map(url -> url.replace(webSite, ""))
                //将结果用,分开拼接
                .collect(Collectors.joining(","));

    }

    /**
     * 根据id查询文章
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //判断id是否为空
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE, "文章的id不能为空");
        }
        WmNews wmNews = getById(id);
        //根据id查询是否存在该文章
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST, "文章不存在，已被删除!");
        }

        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }

    @Override
    public ResponseResult delNews(Integer id) {
        //数据判空
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE, "文章的id不能为空");
        }
        //查询文章当前的状态
        WmNews wmNews = getById(id);
        if (WemediaConstants.WM_NEWS_PUBLISH_STATUS.equals(wmNews.getStatus())
                && WemediaConstants.WM_NEWS_UP.equals(wmNews.getEnable())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "文章处于上架状态,不能被删除!");
        }
        //删除文章素材关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, id));
        //删除文章
        removeById(id);
        return ResponseResult.okResult();
    }

    /**
     * 文章上下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        //判断参数是否为空
        if (dto == null || dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "参数不能为空");
        }
        Short enable = dto.getEnable();
        if (dto.getEnable() == null ||
                (!WemediaConstants.WM_NEWS_UP.equals(enable)&&!WemediaConstants.WM_NEWS_DOWN.equals(enable))){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"上下架状态错误");
        }
        //查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在,未查询到");
        }
        //判断该文章是否已发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH, "非发布状态，先发布才能上架");
        }
        //TODO MQ设置文章上下架的状态
        //update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId()).set(WmNews::getEnable,dto.getEnable()));
        this.update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId, dto.getId()).set(WmNews::getEnable, dto.getEnable()));
        if (dto.getEnable().equals(WemediaConstants.WM_NEWS_UP)) {
            //如果状态时上架状态 修改文章配置中的信息 使用rabbitMq发送消息到队列
            rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                    NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY,wmNews.getArticleId());
            log.info("成功发送文章上架的内容");
        } else {
            //如果是下架状态 修改文章配置表中的信息为下架状态
            rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                    NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY,
                    wmNews.getArticleId());
            log.info("成功发送文章下架的内容");
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 查询自媒体文章列表
     * @param dto
     * @return
     */
    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Override
    public ResponseResult findList(NewsAuthDTO dto) {
        //校验参数
        dto.checkParam();
        //1.起始页
        Integer page = dto.getPage();
        //2.计算当前页索引
        Integer index = (page -1)*dto.getSize();
        //传入索引
        dto.setPage(index);
        //3.对标题进行模糊查询准备
        if (StringUtils.isNotBlank(dto.getTitle())) {
            dto.setTitle("%" + dto.getTitle() +"%" );
        }
        //使用条件进行分页查询
        List<WmNewsVO> wmNewsVOList = wmNewsMapper.findListAndPage(dto);
        long count = wmNewsMapper.findListCount(dto);
        PageResponseResult result = new PageResponseResult(page, dto.getSize(), count, wmNewsVOList);
        result.setHost(webSite);
        return result;
    }
    @Autowired
    private WmUserMapper wmUserMapper;
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //1参数检查
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.查询作者
        WmUser wmUser = null;
        if(wmNews.getUserId() != null){
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }

        //4.封装vo信息返回
        WmNewsVO wmNewsVo = new WmNewsVO();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        if(wmUser != null){
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(webSite);
        return responseResult;
    }

    /**
     * 人工审核
     * @param status  2  失败  4 成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDTO dto) {
        //1.参数检查
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 检查文章状态 不能为9  已发布
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章已发布");
        }
        //3.修改文章状态
        wmNews.setStatus(status);
        if(StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);
        //判断人工审核是否通过 状态为4通过  进行文章发布
        if (wmNews.getStatus().equals(WemediaConstants.WM_NEWS_AUTH_PASS)) {
            long publishTime = wmNews.getPublishTime().getTime();
            long curTime = new Date().getTime();
            long delayTime = publishTime - curTime;
            //TODO 注入rabbitmq的客户端 向mq发送消息
            rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE, //参数1：交换机
                    PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY,  //参数2：路由关键字
                    wmNews.getId(),  //参数3：传递字段
                    message -> { //
                        message.getMessageProperties().setHeader("x-delay",delayTime<=0?0:delayTime);
                        return message;
                    });
            log.info("发布文章通知成功发送 文章id{}",wmNews.getId());
        }


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
